from flask import Blueprint, request, jsonify, g
from extensions import db
from models import Department, Employee, User
from utils import success, error, bad_request, forbidden
from datetime import datetime

# 创建部门管理API蓝图
department_api = Blueprint('department_api', __name__, url_prefix='/api/departments')

# 获取部门列表
@department_api.route('/', methods=['GET'])
def get_departments():
    """获取部门列表"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('page_size', 10, type=int)  # 前端发送的是page_size
        search = request.args.get('search', '')
        
        # 构建查询
        query = Department.query
        
        # 按名称搜索
        if search:
            query = query.filter(Department.name.contains(search))
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        departments = []
        for dept in pagination.items:
            department_data = {
                'id': dept.id,
                'name': dept.name,
                'employee_count': len(dept.employees) if hasattr(dept, 'employees') else 0,
                'created_at': dept.created_at.isoformat(),
                'updated_at': dept.updated_at.isoformat()
            }
            departments.append(department_data)
        
        return success(data={
            'departments': departments,
            'total': pagination.total,
            'pagination': {
                'page': pagination.page,
                'per_page': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(msg=f'获取部门列表失败: {str(e)}').to_response()

# 创建部门
@department_api.route('/', methods=['POST'])
def create_department():
    """创建新部门"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return bad_request(msg='部门名称不能为空').to_response()
        
        # 检查部门名称是否已存在
        existing_dept = Department.query.filter_by(name=data['name']).first()
        if existing_dept:
            return error(code=400, msg='部门名称已存在').to_response()
        
        # 创建部门
        department = Department(
            name=data['name']
        )
        
        db.session.add(department)
        db.session.commit()
        
        return success(data={'id': department.id}, msg='部门创建成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'创建部门失败: {str(e)}').to_response()

# 更新部门信息
@department_api.route('/<int:department_id>', methods=['PUT'])
def update_department(department_id):
    """更新部门信息"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        department = Department.query.get_or_404(department_id)
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        data = request.get_json()
        
        # 检查部门名称是否已存在（排除当前部门）
        if 'name' in data and data['name'] != department.name:
            existing_dept = Department.query.filter(
                Department.name == data['name'],
                Department.id != department_id
            ).first()
            if existing_dept:
                return error(code=400, msg='部门名称已存在').to_response()
        
        # 更新部门信息
        if 'name' in data:
            department.name = data['name']
        
        db.session.commit()
        
        return success(msg='部门信息更新成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'更新部门信息失败: {str(e)}').to_response()

# 删除部门
@department_api.route('/<int:department_id>', methods=['DELETE'])
def delete_department(department_id):
    """删除部门"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user or user.role != 'admin':
            return forbidden(msg='权限不足').to_response()
        
        department = Department.query.get_or_404(department_id)
        
        # 检查部门是否有员工
        if hasattr(department, 'employees') and department.employees:
            return error(code=400, msg='该部门下还有员工，无法删除').to_response()
        
        db.session.delete(department)
        db.session.commit()
        
        return success(msg='部门删除成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'删除部门失败: {str(e)}').to_response()
